About 1646 letters

About 8 minutes

#Python's keyword arguments in functions

When calling a function, arguments can be passed either by position or by name, for example:

# Define function
def attack(attack_power: float, defense_power: float):
    # Calculate damage
    damage: float = attack_power * (1 - defense_power / (defense_power + 100))
    print(f"Dealt {damage} points of damage")

# Positional arguments
attack(100, 10)

# Keyword arguments - order does not matter
attack(defense_power=10, attack_power=100)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Arguments passed by name like this are called keyword arguments.

Keyword arguments must appear at the end of the argument list during a call; otherwise, ambiguity arises. For example, this is invalid:

# Define function
def attack(attack_power: float, defense_power: float):
    damage: float = attack_power * (1 - defense_power / (defense_power + 100))
    print(f"Dealt {damage} points of damage")

# This will cause an error: after keyword argument defense_power=10, 
# it's unclear what 100 refers to (positional or keyword)
attack(defense_power=10, 100)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Positional-Only and Keyword-Only Parameters

You can use / and * in the function parameter list to enforce argument passing rules:

  • Parameters before / can only be passed positionally
  • Parameters after * can only be passed by keyword
  • Parameters between / and * can be passed either way

Example:

def func(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
    pass

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

  • pos1 and pos2 must be passed positionally.
  • kwd1 and kwd2 must be passed as keyword arguments.
  • pos_or_kwd can be passed either way.

Updated: 5/21/2025

Author: PlanC

Created: 5/15/2025